<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-bounce.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"ipvb.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false,"b2t":true,"scrollpercent":true},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="启动MySQL1net start mysql  连接与断开服务器1mysql -h 地址 -P 端口 -u 用户名 -p 密码  跳过权限验证登录MySQL1mysqld --skip-grant-tables">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL命令">
<meta property="og:url" content="https://ipvb.gitee.io/blog/2020/03/15/MySQL/index.html">
<meta property="og:site_name" content="Chenyumeng的博客">
<meta property="og:description" content="启动MySQL1net start mysql  连接与断开服务器1mysql -h 地址 -P 端口 -u 用户名 -p 密码  跳过权限验证登录MySQL1mysqld --skip-grant-tables">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-15T08:06:34.000Z">
<meta property="article:modified_time" content="2020-03-16T09:41:48.821Z">
<meta property="article:author" content="Chenyumeng">
<meta property="article:tag" content="整理">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://ipvb.gitee.io/blog/2020/03/15/MySQL/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>MySQL命令 | Chenyumeng的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <link rel="stylesheet" href="/dist/css/share.min.css">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chenyumeng的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">热爱自己，热爱生活</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">29</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">1</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">32</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="search-pop-overlay">
  <div class="popup search-popup">
      <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

  </div>
</div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/chen-yumeng" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://ipvb.gitee.io/blog/2020/03/15/MySQL/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/touxiang.JPG">
      <meta itemprop="name" content="Chenyumeng">
      <meta itemprop="description" content="用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chenyumeng的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MySQL命令
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-15 16:06:34" itemprop="dateCreated datePublished" datetime="2020-03-15T16:06:34+08:00">2020-03-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-03-16 17:41:48" itemprop="dateModified" datetime="2020-03-16T17:41:48+08:00">2020-03-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index"><span itemprop="name">学习</span></a>
                </span>
            </span>

          
            <span id="/blog/2020/03/15/MySQL/" class="post-meta-item leancloud_visitors" data-flag-title="MySQL命令" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>21k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>19 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="启动MySQL"><a href="#启动MySQL" class="headerlink" title="启动MySQL"></a>启动MySQL</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">net start mysql</span><br></pre></td></tr></table></figure>

<h2 id="连接与断开服务器"><a href="#连接与断开服务器" class="headerlink" title="连接与断开服务器"></a>连接与断开服务器</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql -h 地址 -P 端口 -u 用户名 -p 密码</span><br></pre></td></tr></table></figure>

<h2 id="跳过权限验证登录MySQL"><a href="#跳过权限验证登录MySQL" class="headerlink" title="跳过权限验证登录MySQL"></a>跳过权限验证登录MySQL</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysqld --skip-grant-tables</span><br></pre></td></tr></table></figure>

<a id="more"></a>

<h2 id="修改root密码"><a href="#修改root密码" class="headerlink" title="修改root密码"></a>修改root密码</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">密码加密函数password()</span><br><span class="line"></span><br><span class="line">update mysql.user set password&#x3D;password(&#39;root&#39;);</span><br><span class="line"></span><br><span class="line">SHOW PROCESSLIST -- 显示哪些线程正在运行</span><br><span class="line">SHOW VARIABLES --</span><br></pre></td></tr></table></figure>

<h1 id="数据库操作"><a href="#数据库操作" class="headerlink" title="数据库操作"></a>数据库操作</h1><h2 id="查看当前数据库"><a href="#查看当前数据库" class="headerlink" title="查看当前数据库"></a>查看当前数据库</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select database();</span><br></pre></td></tr></table></figure>

<h2 id="显示当前时间、用户名、数据库版本"><a href="#显示当前时间、用户名、数据库版本" class="headerlink" title="显示当前时间、用户名、数据库版本"></a>显示当前时间、用户名、数据库版本</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select now(), user(), version();</span><br></pre></td></tr></table></figure>

<h2 id="创建库"><a href="#创建库" class="headerlink" title="创建库"></a>创建库</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">create database[ if not exists] 数据库名 数据库选项</span><br><span class="line">    数据库选项：</span><br><span class="line">        CHARACTER SET charset_name</span><br><span class="line">        COLLATE collation_name</span><br></pre></td></tr></table></figure>

<h2 id="查看已有库"><a href="#查看已有库" class="headerlink" title="查看已有库"></a>查看已有库</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show databases[ like &#39;pattern&#39;]</span><br></pre></td></tr></table></figure>

<h2 id="查看当前库信息"><a href="#查看当前库信息" class="headerlink" title="查看当前库信息"></a>查看当前库信息</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show create database 数据库名</span><br></pre></td></tr></table></figure>

<h2 id="修改库的选项信息"><a href="#修改库的选项信息" class="headerlink" title="修改库的选项信息"></a>修改库的选项信息</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alter database 库名 选项信息</span><br></pre></td></tr></table></figure>

<h2 id="删除库"><a href="#删除库" class="headerlink" title="删除库"></a>删除库</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">drop database[ if exists] 数据库名</span><br><span class="line">同时删除该数据库相关的目录及其目录内容</span><br></pre></td></tr></table></figure>

<h1 id="表的操作"><a href="#表的操作" class="headerlink" title="表的操作"></a>表的操作</h1><h2 id="创建表"><a href="#创建表" class="headerlink" title="创建表"></a>创建表</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">create [temporary] table[ if not exists] [库名.]表名 ( 表的结构定义 )[ 表选项]</span><br><span class="line">      每个字段必须有数据类型</span><br><span class="line">      最后一个字段后不能有逗号</span><br><span class="line">      temporary 临时表，会话结束时表自动消失</span><br><span class="line">      对于字段的定义：</span><br><span class="line">          字段名 数据类型 [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT &#39;string&#39;]</span><br></pre></td></tr></table></figure>

<h2 id="表选项"><a href="#表选项" class="headerlink" title="表选项"></a>表选项</h2><h3 id="字符集"><a href="#字符集" class="headerlink" title="字符集"></a>字符集</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">CHARSET &#x3D; charset_name</span><br><span class="line">如果表没有设定，则使用数据库字符集</span><br></pre></td></tr></table></figure>

<h3 id="存储引擎"><a href="#存储引擎" class="headerlink" title="存储引擎"></a>存储引擎</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">ENGINE &#x3D; engine_name    </span><br><span class="line">表在管理数据时采用的不同的数据结构，结构不同会导致处理方式、提供的特性操作等不同</span><br><span class="line">常见的引擎：InnoDB MyISAM Memory&#x2F;Heap BDB Merge Example CSV MaxDB Archive</span><br><span class="line">不同的引擎在保存表的结构和数据时采用不同的方式</span><br><span class="line">MyISAM表文件含义：.frm表定义，.MYD表数据，.MYI表索引</span><br><span class="line">InnoDB表文件含义：.frm表定义，表空间数据和日志文件</span><br><span class="line">SHOW ENGINES -- 显示存储引擎的状态信息</span><br><span class="line">SHOW ENGINE 引擎名 &#123;LOGS|STATUS&#125; -- 显示存储引擎的日志或状态信息</span><br></pre></td></tr></table></figure>

<h3 id="数据文件目录"><a href="#数据文件目录" class="headerlink" title="数据文件目录"></a>数据文件目录</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DATA DIRECTORY &#x3D; &#39;目录&#39;</span><br></pre></td></tr></table></figure>

<h3 id="索引文件目录"><a href="#索引文件目录" class="headerlink" title="索引文件目录"></a>索引文件目录</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">INDEX DIRECTORY &#x3D; &#39;目录&#39;</span><br></pre></td></tr></table></figure>

<h3 id="表注释"><a href="#表注释" class="headerlink" title="表注释"></a>表注释</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">COMMENT &#x3D; &#39;string&#39;</span><br></pre></td></tr></table></figure>

<h3 id="分区选项"><a href="#分区选项" class="headerlink" title="分区选项"></a>分区选项</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">PARTITION BY ... (详细见手册)</span><br></pre></td></tr></table></figure>

<h2 id="查看所有表"><a href="#查看所有表" class="headerlink" title="查看所有表"></a>查看所有表</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SHOW TABLES[ LIKE &#39;pattern&#39;]</span><br><span class="line">SHOW TABLES FROM 表名</span><br></pre></td></tr></table></figure>

<h2 id="查看表机构"><a href="#查看表机构" class="headerlink" title="查看表机构"></a>查看表机构</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SHOW CREATE TABLE 表名    （信息更详细）</span><br><span class="line">DESC 表名 &#x2F; DESCRIBE 表名 &#x2F; EXPLAIN 表名 &#x2F; SHOW COLUMNS FROM 表名 [LIKE &#39;PATTERN&#39;]</span><br><span class="line">SHOW TABLE STATUS [FROM db_name] [LIKE &#39;pattern&#39;]</span><br></pre></td></tr></table></figure>

<h2 id="修改表"><a href="#修改表" class="headerlink" title="修改表"></a>修改表</h2><h3 id="修改表本身的选项"><a href="#修改表本身的选项" class="headerlink" title="修改表本身的选项"></a>修改表本身的选项</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE 表名 表的选项</span><br><span class="line">EG:    ALTER TABLE 表名 ENGINE&#x3D;MYISAM;</span><br></pre></td></tr></table></figure>

<h3 id="对表进行重命名"><a href="#对表进行重命名" class="headerlink" title="对表进行重命名"></a>对表进行重命名</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">RENAME TABLE 原表名 TO 新表名</span><br><span class="line">RENAME TABLE 原表名 TO 库名.表名    （可将表移动到另一个数据库）</span><br><span class="line">-- RENAME可以交换两个表名</span><br></pre></td></tr></table></figure>

<h3 id="修改表的字段机构"><a href="#修改表的字段机构" class="headerlink" title="修改表的字段机构"></a>修改表的字段机构</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE 表名 操作名</span><br></pre></td></tr></table></figure>

<h4 id="操作名"><a href="#操作名" class="headerlink" title="操作名"></a>操作名</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">ADD[ COLUMN] 字段名        -- 增加字段</span><br><span class="line">    AFTER 字段名            -- 表示增加在该字段名后面</span><br><span class="line">    FIRST                -- 表示增加在第一个</span><br><span class="line">ADD PRIMARY KEY(字段名)    -- 创建主键</span><br><span class="line">ADD UNIQUE [索引名] (字段名)-- 创建唯一索引</span><br><span class="line">ADD INDEX [索引名] (字段名)    -- 创建普通索引</span><br><span class="line">ADD </span><br><span class="line">DROP[ COLUMN] 字段名        -- 删除字段</span><br><span class="line">MODIFY[ COLUMN] 字段名 字段属性        -- 支持对字段属性进行修改，不能修改字段名(所有原有属性也需写上)</span><br><span class="line">CHANGE[ COLUMN] 原字段名 新字段名 字段属性        -- 支持对字段名修改</span><br><span class="line">DROP PRIMARY KEY    -- 删除主键(删除主键前需删除其AUTO_INCREMENT属性)</span><br><span class="line">DROP INDEX 索引名    -- 删除索引</span><br><span class="line">DROP FOREIGN KEY 外键    -- 删除外键</span><br></pre></td></tr></table></figure>

<h2 id="删除表"><a href="#删除表" class="headerlink" title="删除表"></a>删除表</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DROP TABLE[ IF EXISTS] 表名 ...</span><br></pre></td></tr></table></figure>

<h2 id="清空表数据"><a href="#清空表数据" class="headerlink" title="清空表数据"></a>清空表数据</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">TRUNCATE [TABLE] 表名</span><br></pre></td></tr></table></figure>

<h2 id="复制表结构"><a href="#复制表结构" class="headerlink" title="复制表结构"></a>复制表结构</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE 表名 LIKE 要复制的表名</span><br></pre></td></tr></table></figure>

<h2 id="复制表结构和数据"><a href="#复制表结构和数据" class="headerlink" title="复制表结构和数据"></a>复制表结构和数据</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE 表名 [AS] SELECT * FROM 要复制的表名</span><br></pre></td></tr></table></figure>

<h2 id="检查表是否有错误"><a href="#检查表是否有错误" class="headerlink" title="检查表是否有错误"></a>检查表是否有错误</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CHECK TABLE tbl_name [, tbl_name] ... [option] ...</span><br></pre></td></tr></table></figure>

<h2 id="优化表"><a href="#优化表" class="headerlink" title="优化表"></a>优化表</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...</span><br></pre></td></tr></table></figure>

<h2 id="修复表"><a href="#修复表" class="headerlink" title="修复表"></a>修复表</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">REPAIR [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ... [QUICK] [EXTENDED] [USE_FRM]</span><br></pre></td></tr></table></figure>



<h2 id="分析表"><a href="#分析表" class="headerlink" title="分析表"></a>分析表</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ANALYZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...</span><br></pre></td></tr></table></figure>

<h1 id="数据操作"><a href="#数据操作" class="headerlink" title="数据操作"></a>数据操作</h1><h2 id="增"><a href="#增" class="headerlink" title="增"></a>增</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">INSERT [INTO] 表名 [(字段列表)] VALUES (值列表)[, (值列表), ...]</span><br><span class="line">-- 如果要插入的值列表包含所有字段并且顺序一致，则可以省略字段列表。</span><br><span class="line">-- 可同时插入多条数据记录！</span><br><span class="line">REPLACE 与 INSERT 完全一样，可互换。</span><br><span class="line">INSERT [INTO] 表名 SET 字段名&#x3D;值[, 字段名&#x3D;值, ...]</span><br></pre></td></tr></table></figure>

<h2 id="查"><a href="#查" class="headerlink" title="查"></a>查</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT 字段列表 FROM 表名[ 其他子句]</span><br><span class="line">-- 可来自多个表的多个字段</span><br><span class="line">-- 其他子句可以不使用</span><br><span class="line">-- 字段列表可以用*代替，表示所有字段</span><br></pre></td></tr></table></figure>

<h2 id="删"><a href="#删" class="headerlink" title="删"></a>删</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">DELETE FROM 表名[ 删除条件子句]</span><br><span class="line">-- 没有条件子句，则会删除全部</span><br></pre></td></tr></table></figure>

<h2 id="改"><a href="#改" class="headerlink" title="改"></a>改</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">UPDATE 表名 SET 字段名&#x3D;新值[, 字段名&#x3D;新值] [更新条件]</span><br></pre></td></tr></table></figure>

<h1 id="字符集编码"><a href="#字符集编码" class="headerlink" title="字符集编码"></a>字符集编码</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">-- MySQL、数据库、表、字段均可设置编码</span><br><span class="line">-- 数据编码与客户端编码不需一致</span><br><span class="line">SHOW VARIABLES LIKE &#39;character_set_%&#39;    -- 查看所有字符集编码项</span><br><span class="line">    character_set_client        客户端向服务器发送数据时使用的编码</span><br><span class="line">    character_set_results        服务器端将结果返回给客户端所使用的编码</span><br><span class="line">    character_set_connection    连接层编码</span><br><span class="line">SET 变量名 &#x3D; 变量值</span><br><span class="line">    set character_set_client &#x3D; gbk;</span><br><span class="line">    set character_set_results &#x3D; gbk;</span><br><span class="line">    set character_set_connection &#x3D; gbk;</span><br><span class="line">SET NAMES GBK;    -- 相当于完成以上三个设置</span><br><span class="line">-- 校对集</span><br><span class="line">    校对集用以排序</span><br><span class="line">    SHOW CHARACTER SET [LIKE &#39;pattern&#39;]&#x2F;SHOW CHARSET [LIKE &#39;pattern&#39;]    查看所有字符集</span><br><span class="line">    SHOW COLLATION [LIKE &#39;pattern&#39;]        查看所有校对集</span><br><span class="line">    charset 字符集编码        设置字符集编码</span><br><span class="line">    collate 校对集编码        设置校对集编码</span><br></pre></td></tr></table></figure>



<h1 id="数据类型（列类型）"><a href="#数据类型（列类型）" class="headerlink" title="数据类型（列类型）"></a>数据类型（列类型）</h1><h2 id="数值类型"><a href="#数值类型" class="headerlink" title="数值类型"></a>数值类型</h2><h3 id="整型"><a href="#整型" class="headerlink" title="整型"></a>整型</h3><table>
<thead>
<tr>
<th>类型</th>
<th>字节</th>
<th>范围（有符号位）</th>
</tr>
</thead>
<tbody><tr>
<td>smallint</td>
<td>2字节</td>
<td>-32768 ~ 32767</td>
</tr>
<tr>
<td>mediumint</td>
<td>3字节</td>
<td>-8388608 ~ 8388607</td>
</tr>
<tr>
<td>int</td>
<td>4字节</td>
<td></td>
</tr>
<tr>
<td>bigint</td>
<td>8字节</td>
<td></td>
</tr>
</tbody></table>
<p> int(M)    M表示总位数</p>
<ul>
<li>默认存在符号位，unsigned 属性修改</li>
<li>显示宽度，如果某个数不够定义字段时设置的位数，则前面以0补填，zerofill 属性修改<br>例：int(5)    插入一个数’123’，补填后为’00123’</li>
<li>在满足要求的情况下，越小越好。</li>
<li>1表示bool值真，0表示bool值假。MySQL没有布尔类型，通过整型0和1表示。常用tinyint(1)表示布尔型。</li>
</ul>
<h3 id="浮点型"><a href="#浮点型" class="headerlink" title="浮点型"></a>浮点型</h3><h3 id=""><a href="#" class="headerlink" title=""></a></h3><table>
<thead>
<tr>
<th>类型</th>
<th>字节</th>
<th>范围（有符号位）</th>
</tr>
</thead>
<tbody><tr>
<td>float(单精度)</td>
<td>4字节</td>
<td></td>
</tr>
<tr>
<td>double(双精度)</td>
<td>8字节</td>
<td></td>
</tr>
</tbody></table>
<p> 浮点型既支持符号位 unsigned 属性，也支持显示宽度 zerofill 属性。<br>        不同于整型，前后均会补填0.<br>定义浮点型时，需指定总位数和小数位数。<br>        float(M, D)        double(M, D)<br>        M表示总位数，D表示小数位数。<br>        M和D的大小会决定浮点数的范围。不同于整型的固定范围。<br>        M既表示总位数（不包括小数点和正负号），也表示显示宽度（所有显示符号均包括）。<br>        支持科学计数法表示。<br>        浮点数表示近似值。</p>
<h3 id="定点数"><a href="#定点数" class="headerlink" title="定点数"></a>定点数</h3><p>​    decimal    – 可变长度<br>​    decimal(M, D)    M也表示总位数，D表示小数位数。<br>​    保存一个精确的数值，不会发生数据的改变，不同于浮点数的四舍五入。<br>​    将浮点数转换为字符串来保存，每9位数字保存为4个字节。</p>
<h2 id="字符串类型"><a href="#字符串类型" class="headerlink" title="字符串类型"></a>字符串类型</h2><h3 id="char-varchar"><a href="#char-varchar" class="headerlink" title="char, varchar"></a>char, varchar</h3><p> char    定长字符串，速度快，但浪费空间<br> varchar    变长字符串，速度慢，但节省空间<br> M表示能存储的最大长度，此长度是字符数，非字节数。<br> 不同的编码，所占用的空间不同。<br> char,最多255个字符，与编码无关。<br> varchar,最多65535字符，与编码有关。<br> 一条有效记录最大不能超过65535个字节。<br>     utf8 最大为21844个字符，gbk 最大为32766个字符，latin1 最大为65532个字符<br> varchar 是变长的，需要利用存储空间保存 varchar 的长度，如果数据小于255个字节，则采用一个字节来保存长度，反之需要两个字节来保存。<br> varchar 的最大有效长度由最大行大小和使用的字符集确定。<br> 最大有效长度是65532字节，因为在varchar存字符串时，第一个字节是空的，不存在任何数据，然后还需两个字节来存放字符串的长度，所以有效长度是64432-1-2=65532字节。<br> 例：若一个表定义为 CREATE TABLE tb(c1 int, c2 char(30), c3 varchar(N)) charset=utf8; 问N的最大值是多少？ 答：(65535-1-2-4-30*3)/3</p>
<h3 id="blob-text"><a href="#blob-text" class="headerlink" title="blob, text"></a>blob, text</h3><p>​    blob 二进制字符串（字节字符串）<br>​        tinyblob, blob, mediumblob, longblob<br>​    text 非二进制字符串（字符字符串）<br>​        tinytext, text, mediumtext, longtext<br>​    text 在定义时，不需要定义长度，也不会计算总长度。<br>​    text 类型在定义时，不可给default值</p>
<h3 id="binary-varbinary"><a href="#binary-varbinary" class="headerlink" title="binary, varbinary"></a>binary, varbinary</h3><p>​    类似于char和varchar，用于保存二进制字符串，也就是保存字节字符串而非字符字符串。<br>​    char, varchar, text 对应 binary, varbinary, blob.</p>
<h2 id="日期时间类型"><a href="#日期时间类型" class="headerlink" title="日期时间类型"></a>日期时间类型</h2><p>一般用整型保存时间戳，因为PHP可以很方便的将时间戳进行格式化。</p>
<table>
<thead>
<tr>
<th align="center">类型</th>
<th align="center">字节</th>
<th align="right">意思</th>
<th align="center">大小</th>
<th align="left"></th>
</tr>
</thead>
<tbody><tr>
<td align="center">datetime</td>
<td align="center">8字节</td>
<td align="right">日期及时间</td>
<td align="center">1000-01-01 00:00:00 到 9999-12-31 23:59:59</td>
<td align="left">“YYYY-MM-DD hh:mm:ss”</td>
</tr>
<tr>
<td align="center">date</td>
<td align="center">3字节</td>
<td align="right">日期</td>
<td align="center">1000-01-01 到 9999-12-31</td>
<td align="left">“YYYY-MM-DD”<br />“YY-MM-DD”<br />“YYYYMMDD”<br />“YYMMDD”<br />“YYYYMMDD””YYMMDD“</td>
</tr>
<tr>
<td align="center">timestamp</td>
<td align="center">4字节</td>
<td align="right">时间戳</td>
<td align="center">19700101000000 到 2038-01-19 03:14:07</td>
<td align="left">“YY-MM-DDhh:mm:ss”<br />“YYYYMMDDhhmmss”<br />“YYMMDDhhmmss”<br />”YYYYMMDDhhmmss“            ”YYMMDDhhmmss“</td>
</tr>
<tr>
<td align="center">time</td>
<td align="center">3字节</td>
<td align="right">时间</td>
<td align="center">-838:59:59 到 838:59:59</td>
<td align="left">“hh:mm:ss”<br />“hhmmss”<br />“hhmmss”</td>
</tr>
<tr>
<td align="center">year</td>
<td align="center">1字节</td>
<td align="right">年份</td>
<td align="center">1901 - 2155</td>
<td align="left">“YYYY”  “YY”</td>
</tr>
</tbody></table>
<h2 id="枚举和集合"><a href="#枚举和集合" class="headerlink" title="枚举和集合"></a>枚举和集合</h2><h3 id="枚举-enum"><a href="#枚举-enum" class="headerlink" title="枚举(enum)"></a>枚举(enum)</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">enum(val1, val2, val3...)</span><br></pre></td></tr></table></figure>

<p> 在已知的值中进行单选。最大数量为65535.<br> 枚举值在保存时，以2个字节的整型(smallint)保存。每个枚举值，按保存的位置顺序，从1开始逐一递增。<br> 表现为字符串类型，存储却是整型。<br> NULL值的索引是NULL。<br> 空字符串错误值的索引值是0。</p>
<h3 id="集合（set）"><a href="#集合（set）" class="headerlink" title="集合（set）"></a>集合（set）</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">set(val1, val2, val3...)</span><br></pre></td></tr></table></figure>

<p>​    create table tab ( gender set(‘男’, ‘女’, ‘无’) );<br>​    insert into tab values (‘男, 女’);<br>​    最多可以有64个不同的成员。以bigint存储，共8个字节。采取位运算的形式。<br>​    当创建表时，SET成员值的尾部空格将自动被删除。</p>
<h2 id="选择类型"><a href="#选择类型" class="headerlink" title="选择类型"></a>选择类型</h2><h3 id="PHP角度"><a href="#PHP角度" class="headerlink" title="PHP角度"></a>PHP角度</h3><ol>
<li>功能满足</li>
<li>存储空间尽量小，处理效率更高</li>
<li>考虑兼容问题</li>
</ol>
<h3 id="IP存储"><a href="#IP存储" class="headerlink" title="IP存储"></a>IP存储</h3><ol>
<li>只需存储，可用字符串</li>
<li>如果需计算，查找等，可存储为4个字节的无符号int，即unsigned<br>1) PHP函数转换<pre><code>ip2long可转换为整型，但会出现携带符号问题。需格式化为无符号的整型。
利用sprintf函数格式化字符串
sprintf(&quot;%u&quot;, ip2long(&apos;192.168.3.134&apos;));
然后用long2ip将整型转回IP字符串</code></pre>2) MySQL函数转换(无符号整型，UNSIGNED)<pre><code>INET_ATON(&apos;127.0.0.1&apos;) 将IP转为整型
INET_NTOA(2130706433) 将整型转为IP</code></pre></li>
</ol>
<h1 id="列属性（列约束）"><a href="#列属性（列约束）" class="headerlink" title="列属性（列约束）"></a>列属性（列约束）</h1><h2 id="主键"><a href="#主键" class="headerlink" title="主键"></a>主键</h2><ul>
<li>能唯一标识记录的字段，可以作为主键。</li>
<li>一个表只能有一个主键。</li>
<li>主键具有唯一性。</li>
<li>声明字段时，用 primary key 标识。<br>也可以在字段列表之后声明<pre><code>例：create table tab ( id int, stu varchar(10), primary key (id));</code></pre></li>
<li>主键字段的值不能为null。</li>
<li>主键可以由多个字段共同组成。此时需要在字段列表后声明的方法。<br>例：create table tab ( id int, stu varchar(10), age int, primary key (stu, age));</li>
</ul>
<h2 id="unique-唯一索引（唯一约束）"><a href="#unique-唯一索引（唯一约束）" class="headerlink" title="unique 唯一索引（唯一约束）"></a>unique 唯一索引（唯一约束）</h2><p>使得某字段的值也不能重复。</p>
<h2 id="null-约束"><a href="#null-约束" class="headerlink" title="null 约束"></a>null 约束</h2><p>null不是数据类型，是列的一个属性。<br>表示当前列是否可以为null，表示什么都没有。<br>null, 允许为空。默认。<br>not null, 不允许为空。<br>insert into tab values (null, ‘val’);<br>    – 此时表示将第一个字段的值设为null, 取决于该字段是否允许为null</p>
<h2 id="default-默认值属性"><a href="#default-默认值属性" class="headerlink" title="default 默认值属性"></a>default 默认值属性</h2><p>当前字段的默认值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">insert into tab values (default, &#39;val&#39;);    -- 此时表示强制使用默认值。</span><br><span class="line">create table tab ( add_time timestamp default current_timestamp );</span><br><span class="line">-- 表示将当前时间的时间戳设为默认值。</span><br><span class="line">current_date, current_time</span><br></pre></td></tr></table></figure>



<h2 id="auto-increment-自动增长约束"><a href="#auto-increment-自动增长约束" class="headerlink" title="auto_increment 自动增长约束"></a>auto_increment 自动增长约束</h2><p>自动增长必须为索引（主键或unique）<br>只能存在一个字段为自动增长。<br>默认为1开始自动增长。可以通过表属性 auto_increment = x进行设置，或 alter table tbl auto_increment = x;</p>
<h2 id="comment-注释"><a href="#comment-注释" class="headerlink" title="comment 注释"></a>comment 注释</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">-- 例：</span><br><span class="line">create table tab ( id int ) comment &#39;注释内容&#39;;</span><br></pre></td></tr></table></figure>

<h2 id="foreign-key-外键约束"><a href="#foreign-key-外键约束" class="headerlink" title="foreign key 外键约束"></a>foreign key 外键约束</h2><p>用于限制主表与从表数据完整性。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">alter table t1 add constraint &#96;t1_t2_fk&#96; foreign key (t1_id) references t2(id);</span><br><span class="line">    -- 将表t1的t1_id外键关联到表t2的id字段。</span><br><span class="line">    -- 每个外键都有一个名字，可以通过 constraint 指定</span><br></pre></td></tr></table></figure>

<p>存在外键的表，称之为从表（子表），外键指向的表，称之为主表（父表）。</p>
<p>作用：保持数据一致性，完整性，主要目的是控制存储在外键表（从表）中的数据。</p>
<p>MySQL中，可以对InnoDB引擎使用外键约束：<br>语法：<br>foreign key (外键字段） references 主表名 (关联字段) [主表记录删除时的动作] [主表记录更新时的动作]<br>此时需要检测一个从表的外键需要约束为主表的已存在的值。外键在没有关联的情况下，可以设置为null.前提是该外键列，没有not null。</p>
<p>可以不指定主表记录更改或更新时的动作，那么此时主表的操作被拒绝。</p>
<h2 id="如果指定了-on-update-或-on-delete：在删除或更新时，有如下几个操作可以选择："><a href="#如果指定了-on-update-或-on-delete：在删除或更新时，有如下几个操作可以选择：" class="headerlink" title="如果指定了 on update 或 on delete：在删除或更新时，有如下几个操作可以选择："></a>如果指定了 on update 或 on delete：在删除或更新时，有如下几个操作可以选择：</h2><ol>
<li>cascade，级联操作。主表数据被更新（主键值更新），从表也被更新（外键值更新）。主表记录被删除，从表相关记录也被删除。</li>
<li>set null，设置为null。主表数据被更新（主键值更新），从表的外键被设置为null。主表记录被删除，从表相关记录外键被设置成null。但注意，要求该外键列，没有not null属性约束。</li>
<li>restrict，拒绝父表删除和更新。</li>
</ol>
<p>注意，外键只被InnoDB存储引擎所支持。其他引擎是不支持的。</p>
<h1 id="建表规范"><a href="#建表规范" class="headerlink" title="建表规范"></a>建表规范</h1><p>Normal Format, NF</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">- 每个表保存一个实体信息</span><br><span class="line">        - 每个具有一个ID字段作为主键</span><br><span class="line">        - ID主键 + 原子表</span><br><span class="line">    -- 1NF, 第一范式</span><br><span class="line">                字段不能再分，就满足第一范式。</span><br><span class="line">    -- 2NF, 第二范式</span><br><span class="line">                满足第一范式的前提下，不能出现部分依赖。</span><br><span class="line">                消除符合主键就可以避免部分依赖。增加单列关键字。</span><br><span class="line">    -- 3NF, 第三范式</span><br><span class="line">                满足第二范式的前提下，不能出现传递依赖。</span><br><span class="line">                某个字段依赖于主键，而有其他字段依赖于该字段。这就是传递依赖。</span><br><span class="line">                将一个实体信息的数据放在一个表内实现。</span><br></pre></td></tr></table></figure>

<h1 id="select"><a href="#select" class="headerlink" title="select"></a>select</h1><p>select [all|distinct] select_expr from -&gt; where -&gt; group by [合计函数] -&gt; having -&gt; order by -&gt; limit</p>
<h2 id="select-expr"><a href="#select-expr" class="headerlink" title="select_expr"></a>select_expr</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">-- 可以用 * 表示所有字段。</span><br><span class="line">select * from tb;</span><br><span class="line">-- 可以使用表达式（计算公式、函数调用、字段也是个表达式）</span><br><span class="line">select stu, 29+25, now() from tb;</span><br><span class="line">-- 可以为每个列使用别名。适用于简化列标识，避免多个列标识符重复。</span><br><span class="line">-- 使用 as 关键字，也可省略 as.</span><br><span class="line">select stu+10 as add10 from tb;</span><br></pre></td></tr></table></figure>

<h2 id="from-子句"><a href="#from-子句" class="headerlink" title="from 子句"></a>from 子句</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">-- 用于标识查询来源。</span><br><span class="line">-- 可以为表起别名。使用as关键字。</span><br><span class="line">select * from tb1 as tt, tb2 as bb;</span><br><span class="line">-- from子句后，可以同时出现多个表。</span><br><span class="line">-- 多个表会横向叠加到一起，而数据会形成一个笛卡尔积。</span><br><span class="line">select * from tb1, tb2;</span><br></pre></td></tr></table></figure>

<h2 id="where-子句"><a href="#where-子句" class="headerlink" title="where 子句"></a>where 子句</h2><p>从from获得的数据源中进行筛选。<br> 整型1表示真，0表示假。<br>表达式由运算符和运算数组成。<br>运算数：变量（字段）、值、函数返回值<br>运算符：<br>=, &lt;=&gt;, &lt;&gt;, !=, &lt;=, &lt;, &gt;=, &gt;, !, &amp;&amp;, ||, in (not) null, (not) like, (not) in, (not) between and, is (not), and, or, not, xor is/is not 加上ture/false/unknown，检验某个值的真假&lt;=&gt;与&lt;&gt;功能相同，&lt;=&gt;可用于null比较</p>
<h2 id="group-by-子句-分组子句"><a href="#group-by-子句-分组子句" class="headerlink" title="group by 子句, 分组子句"></a>group by 子句, 分组子句</h2><p>group by 字段/别名 [排序方式]<br>分组后会进行排序。升序：ASC，降序：DESC<br>以下[合计函数]需配合 group by 使用：<br>count 返回不同的非NULL值数目    count(*)、count(字段)<br>sum 求和<br>max 求最大值<br>min 求最小值<br>avg 求平均值</p>
<p>group_concat 返回带有来自一个组的连接的非NULL值的字符串结果。组内字符串连接。</p>
<h2 id="having-子句，条件子句"><a href="#having-子句，条件子句" class="headerlink" title="having 子句，条件子句"></a>having 子句，条件子句</h2><p>与 where 功能、用法相同，执行时机不同。<br>where 在开始时执行检测数据，对原数据进行过滤。<br>having 对筛选出的结果再次进行过滤。<br>having 字段必须是查询出来的，where 字段必须是数据表存在的。<br>where 不可以使用字段的别名，having 可以。因为执行WHERE代码时，可能尚未确定列值。<br>where 不可以使用合计函数。一般需用合计函数才会用 having<br>SQL标准要求HAVING必须引用GROUP BY子句中的列或用于合计函数中的列。</p>
<h2 id="order-by-子句，排序子句"><a href="#order-by-子句，排序子句" class="headerlink" title="order by 子句，排序子句"></a>order by 子句，排序子句</h2><p>order by 排序字段/别名 排序方式 [,排序字段/别名 排序方式]…<br>升序：ASC，降序：DESC<br>支持多个字段的排序。</p>
<h2 id="limit-子句，限制结果数量子句"><a href="#limit-子句，限制结果数量子句" class="headerlink" title="limit 子句，限制结果数量子句"></a>limit 子句，限制结果数量子句</h2><p>仅对处理好的结果进行数量限制。将处理好的结果的看作是一个集合，按照记录出现的顺序，索引从0开始。<br>limit 起始位置, 获取条数<br>省略第一个参数，表示从索引0开始。limit 获取条数</p>
<h2 id="distinct-all-选项"><a href="#distinct-all-选项" class="headerlink" title="distinct, all 选项"></a>distinct, all 选项</h2><p>distinct 去除重复记录<br>默认为 all, 全部记录</p>
<h1 id="UNION"><a href="#UNION" class="headerlink" title="UNION"></a>UNION</h1><p>将多个select查询的结果组合成一个结果集合。<br>SELECT … UNION [ALL|DISTINCT] SELECT …<br>默认 DISTINCT 方式，即所有返回的行都是唯一的<br>建议，对每个SELECT查询加上小括号包裹。<br>ORDER BY 排序时，需加上 LIMIT 进行结合。<br>需要各select查询的字段数量一样。<br>每个select查询的字段列表(数量、类型)应一致，因为结果中的字段名以第一条select语句为准。</p>
<h1 id="子查询"><a href="#子查询" class="headerlink" title="子查询"></a>子查询</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">- 子查询需用括号包裹。</span><br><span class="line"></span><br><span class="line">## -- from型</span><br><span class="line"></span><br><span class="line">​    from后要求是一个表，必须给子查询结果取个别名。</span><br><span class="line"></span><br><span class="line">    - 简化每个查询内的条件。</span><br><span class="line">    - from型需将结果生成一个临时表格，可用以原表的锁定的释放。</span><br><span class="line">        - 子查询返回一个表，表型子查询。</span><br><span class="line">        select * from (select * from tb where id&gt;0) as subfrom where id&gt;1;</span><br><span class="line">-- where型</span><br><span class="line">        - 子查询返回一个值，标量子查询。</span><br><span class="line">        - 不需要给子查询取别名。</span><br><span class="line">          - where子查询内的表，不能直接用以更新。</span><br><span class="line">          select * from tb where money &#x3D; (select max(money) from tb);</span><br><span class="line">          -- 列子查询</span><br><span class="line">      如果子查询结果返回的是一列。</span><br><span class="line">      使用 in 或 not in 完成查询</span><br><span class="line">    exists 和 not exists 条件</span><br><span class="line">        如果子查询返回数据，则返回1或0。常用于判断条件。</span><br><span class="line">        select column1 from t1 where exists (select * from t2);</span><br><span class="line">          -- 行子查询</span><br><span class="line">      查询条件是一个行。</span><br><span class="line">      select * from t1 where (id, gender) in (select id, gender from t2);</span><br><span class="line">      行构造符：(col1, col2, ...) 或 ROW(col1, col2, ...)</span><br><span class="line">      行构造符通常用于与对能返回两个或两个以上列的子查询进行比较。</span><br></pre></td></tr></table></figure>

<h2 id="特殊运算符"><a href="#特殊运算符" class="headerlink" title="特殊运算符"></a>特殊运算符</h2><p>​    != all()    相当于 not in<br>​    = some()    相当于 in。any 是 some 的别名<br>​    != some()    不等同于 not in，不等于其中某一个。<br>​    all, some 可以配合其他运算符一起使用。</p>
<h1 id="连接查询-join"><a href="#连接查询-join" class="headerlink" title="连接查询(join)"></a>连接查询(join)</h1><p>​    将多个表的字段进行连接，可以指定连接条件。</p>
<h2 id="内连接-inner-join"><a href="#内连接-inner-join" class="headerlink" title="内连接(inner join)"></a>内连接(inner join)</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- 默认就是内连接，可省略inner。</span><br><span class="line">    - 只有数据存在时才能发送连接。即连接结果不能出现空行。</span><br><span class="line">    on 表示连接条件。其条件表达式与where类似。也可以省略条件（表示条件永远为真）</span><br><span class="line">    也可用where表示连接条件。</span><br><span class="line">    还有 using, 但需字段名相同。 using(字段名)</span><br></pre></td></tr></table></figure>

<h2 id="交叉连接-cross-join"><a href="#交叉连接-cross-join" class="headerlink" title="交叉连接 cross join"></a>交叉连接 cross join</h2><p>​        即，没有条件的内连接。<br>​        select * from tb1 cross join tb2;</p>
<h2 id="外连接-outer-join"><a href="#外连接-outer-join" class="headerlink" title="外连接(outer join)"></a>外连接(outer join)</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">- 如果数据不存在，也会出现在连接结果中。</span><br><span class="line">    </span><br><span class="line">    ### -- 左外连接 left join</span><br><span class="line"></span><br><span class="line">    如果数据不存在，左表记录会出现，而右表为null填充</span><br><span class="line"></span><br><span class="line">###     -- 右外连接 right join</span><br><span class="line"></span><br><span class="line">如果数据不存在，右表记录会出现，而左表为null填充</span><br><span class="line">-- 自然连接(natural join)</span><br><span class="line">    自动判断连接条件完成连接。</span><br><span class="line">    相当于省略了using，会自动查找相同字段名。</span><br><span class="line">    natural join</span><br><span class="line">    natural left join</span><br><span class="line">    natural right join</span><br></pre></td></tr></table></figure>

<p>select info.id, info.name, info.stu_num, extra_info.hobby, extra_info.sex from info, extra_info where info.stu_num = extra_info.stu_id;</p>
<h1 id="导入导出"><a href="#导入导出" class="headerlink" title="导入导出"></a>导入导出</h1><p>select * into outfile 文件地址 [控制格式] from 表名;    – 导出表数据<br>load data [local] infile 文件地址 [replace|ignore] into table 表名 [控制格式];    – 导入数据<br>    生成的数据默认的分隔符是制表符<br>    local未指定，则数据文件必须在服务器上<br>    replace 和 ignore 关键词控制对现有的唯一键记录的重复的处理</p>
<h2 id="控制格式"><a href="#控制格式" class="headerlink" title="控制格式"></a>控制格式</h2><p>fields    控制字段格式<br>默认：fields terminated by ‘\t’ enclosed by ‘’ escaped by ‘\‘<br>    terminated by ‘string’    – 终止<br>    enclosed by ‘char’        – 包裹<br>    escaped by ‘char’        – 转义<br>    – 示例：<br>        SELECT a,b,a+b INTO OUTFILE ‘/tmp/result.text’<br>        FIELDS TERMINATED BY ‘,’ OPTIONALLY ENCLOSED BY ‘“‘<br>        LINES TERMINATED BY ‘\n’<br>        FROM test_table;<br>lines    控制行格式<br>默认：lines terminated by ‘\n’<br>    terminated by ‘string’    – 终止</p>
<h1 id="insert"><a href="#insert" class="headerlink" title="insert"></a>insert</h1><p>select语句获得的数据可以用insert插入。</p>
<p>可以省略对列的指定，要求 values () 括号内，提供给了按照列顺序出现的所有字段的值。<br>    或者使用set语法。<br>    insert into tbl_name set field=value,…；</p>
<p>可以一次性使用多个值，采用(), (), ();的形式。<br>    insert into tbl_name values (), (), ();</p>
<p>可以在列值指定时，使用表达式。<br>    insert into tbl_name values (field_value, 10+10, now());<br>可以使用一个特殊值 default，表示该列使用默认值。<br>    insert into tbl_name values (field_value, default);</p>
<p>可以通过一个查询的结果，作为需要插入的值。<br>    insert into tbl_name select …;</p>
<p>可以指定在插入的值出现主键（或唯一索引）冲突时，更新其他非主键列的信息。<br>    insert into tbl_name values/set/select on duplicate key update 字段=值, …;</p>
<h1 id="delete"><a href="#delete" class="headerlink" title="delete"></a>delete</h1><p>DELETE FROM tbl_name [WHERE where_definition] [ORDER BY …] [LIMIT row_count]</p>
<p>按照条件删除</p>
<p>指定删除的最多记录数。Limit</p>
<p>可以通过排序条件删除。order by + limit</p>
<p>支持多表删除，使用类似连接语法。<br>delete from 需要删除数据多表1，表2 using 表连接操作 条件。</p>
<h1 id="truncate"><a href="#truncate" class="headerlink" title="truncate"></a>truncate</h1><p>TRUNCATE [TABLE] tbl_name<br>清空数据<br>删除重建表</p>
<p>区别：<br>1，truncate 是删除表再创建，delete 是逐条删除<br>2，truncate 重置auto_increment的值。而delete不会<br>3，truncate 不知道删除了几条，而delete知道。<br>4，当被用于带分区的表时，truncate 会保留分区</p>
<h1 id="备份与还原"><a href="#备份与还原" class="headerlink" title="备份与还原"></a>备份与还原</h1><p>备份，将数据的结构与表内数据保存起来。<br>利用 mysqldump 指令完成。</p>
<h2 id="导出"><a href="#导出" class="headerlink" title="导出"></a>导出</h2><ol>
<li>导出一张表<br>mysqldump -u用户名 -p密码 库名 表名 &gt; 文件名(D:/a.sql)</li>
<li>导出多张表<br>mysqldump -u用户名 -p密码 库名 表1 表2 表3 &gt; 文件名(D:/a.sql)</li>
<li>导出所有表<br>mysqldump -u用户名 -p密码 库名 &gt; 文件名(D:/a.sql)</li>
<li>导出一个库<br>mysqldump -u用户名 -p密码 -B 库名 &gt; 文件名(D:/a.sql)</li>
</ol>
<p>可以-w携带备份条件</p>
<h2 id="导入"><a href="#导入" class="headerlink" title="导入"></a>导入</h2><ol>
<li>在登录mysql的情况下：<br>source  备份文件</li>
<li>在不登录的情况下<br>mysql -u用户名 -p密码 库名 &lt; 备份文件</li>
</ol>
<h1 id="视图"><a href="#视图" class="headerlink" title="视图"></a>视图</h1><p>什么是视图：<br>    视图是一个虚拟表，其内容由查询定义。同真实的表一样，视图包含一系列带有名称的列和行数据。但是，视图并不在数据库中以存储的数据值集形式存在。行和列数据来自由定义视图的查询所引用的表，并且在引用视图时动态生成。<br>    视图具有表结构文件，但不存在数据文件。<br>    对其中所引用的基础表来说，视图的作用类似于筛选。定义视图的筛选可以来自当前或其它数据库的一个或多个表，或者其它视图。通过视图进行查询没有任何限制，通过它们进行数据修改时的限制也很少。<br>    视图是存储在数据库中的查询的sql语句，它主要出于两种原因：安全原因，视图可以隐藏一些数据，如：社会保险基金表，可以用视图只显示姓名，地址，而不显示社会保险号和工资数等，另一原因是可使复杂的查询易于理解和使用。</p>
<h2 id="创建视图"><a href="#创建视图" class="headerlink" title="创建视图"></a>创建视图</h2><p>CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW view_name [(column_list)] AS select_statement</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- 视图名必须唯一，同时不能与表重名。</span><br><span class="line">    - 视图可以使用select语句查询到的列名，也可以自己指定相应的列名。</span><br><span class="line">    - 可以指定视图执行的算法，通过ALGORITHM指定。</span><br><span class="line">    - column_list如果存在，则数目必须等于SELECT语句检索的列数</span><br></pre></td></tr></table></figure>

<h2 id="查看结构"><a href="#查看结构" class="headerlink" title="查看结构"></a>查看结构</h2><p>​    SHOW CREATE VIEW view_name </p>
<h2 id="删除视图"><a href="#删除视图" class="headerlink" title="删除视图"></a>删除视图</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- 删除视图后，数据依然存在。</span><br><span class="line">    - 可同时删除多个视图。</span><br><span class="line">    DROP VIEW [IF EXISTS] view_name ...</span><br></pre></td></tr></table></figure>

<h2 id="修改视图结构"><a href="#修改视图结构" class="headerlink" title="修改视图结构"></a>修改视图结构</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- 一般不修改视图，因为不是所有的更新视图都会映射到表上。</span><br><span class="line">    ALTER VIEW view_name [(column_list)] AS select_statement</span><br></pre></td></tr></table></figure>

<h2 id="视图作用"><a href="#视图作用" class="headerlink" title="视图作用"></a>视图作用</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1. 简化业务逻辑</span><br><span class="line">    2. 对客户端隐藏真实的表结构</span><br></pre></td></tr></table></figure>

<h2 id="视图算法-ALGORITHM"><a href="#视图算法-ALGORITHM" class="headerlink" title="视图算法(ALGORITHM)"></a>视图算法(ALGORITHM)</h2><p>​    MERGE        合并<br>​        将视图的查询语句，与外部查询需要先合并再执行！<br>​    TEMPTABLE    临时表<br>​        将视图执行完毕后，形成临时表，再做外层查询！<br>​    UNDEFINED    未定义(默认)，指的是MySQL自主去选择相应的算法。</p>
<h1 id="事务-transaction"><a href="#事务-transaction" class="headerlink" title="事务(transaction)"></a>事务(transaction)</h1><p>事务是指逻辑上的一组操作，组成这组操作的各个单元，要不全成功要不全失败。 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- 支持连续SQL的集体成功或集体撤销。</span><br><span class="line">    - 事务是数据库在数据晚自习方面的一个功能。</span><br><span class="line">    - 需要利用 InnoDB 或 BDB 存储引擎，对自动提交的特性支持完成。</span><br><span class="line">    - InnoDB被称为事务安全型引擎。</span><br></pre></td></tr></table></figure>

<h2 id="事务开启"><a href="#事务开启" class="headerlink" title="事务开启"></a>事务开启</h2><p>​    START TRANSACTION; 或者 BEGIN;<br>​    开启事务后，所有被执行的SQL语句均被认作当前事务内的SQL语句。</p>
<h2 id="事务提交"><a href="#事务提交" class="headerlink" title="事务提交"></a>事务提交</h2><p>​    COMMIT;</p>
<h2 id="事务回滚"><a href="#事务回滚" class="headerlink" title="事务回滚"></a>事务回滚</h2><p>​    ROLLBACK;<br>​    如果部分操作发生问题，映射到事务开启前。</p>
<h2 id="事务的特性"><a href="#事务的特性" class="headerlink" title="事务的特性"></a>事务的特性</h2><h3 id="原子性（Atomicity）"><a href="#原子性（Atomicity）" class="headerlink" title="原子性（Atomicity）"></a>原子性（Atomicity）</h3><p>事务是一个不可分割的工作单位，事务中的操作要么都发生，要么都不发生。</p>
<h3 id="一致性（Consistency）"><a href="#一致性（Consistency）" class="headerlink" title="一致性（Consistency）"></a>一致性（Consistency）</h3><p>事务前后数据的完整性必须保持一致。</p>
<ul>
<li>事务开始和结束时，外部数据一致</li>
<li>在整个事务过程中，操作是连续的</li>
</ul>
<h3 id="隔离性（Isolation）"><a href="#隔离性（Isolation）" class="headerlink" title="隔离性（Isolation）"></a>隔离性（Isolation）</h3><p>多个用户并发访问数据库时，一个用户的事务不能被其它用户的事物所干扰，多个并发事务之间的数据要相互隔离。</p>
<h3 id="持久性（Durability）"><a href="#持久性（Durability）" class="headerlink" title="持久性（Durability）"></a>持久性（Durability）</h3><p>一个事务一旦被提交，它对数据库中的数据改变就是永久性的。</p>
<h2 id="事务的实现"><a href="#事务的实现" class="headerlink" title="事务的实现"></a>事务的实现</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1. 要求是事务支持的表类型</span><br><span class="line">2. 执行一组相关的操作前开启事务</span><br><span class="line">3. 整组操作完成后，都成功，则提交；如果存在失败，选择回滚，则会回到事务开始的备份点。</span><br></pre></td></tr></table></figure>

<h2 id="事务的原理"><a href="#事务的原理" class="headerlink" title="事务的原理"></a>事务的原理</h2><p>​    利用InnoDB的自动提交(autocommit)特性完成。<br>​    普通的MySQL执行语句后，当前的数据提交操作均可被其他客户端可见。<br>​    而事务是暂时关闭“自动提交”机制，需要commit提交持久化数据操作。</p>
<h2 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1. 数据定义语言（DDL）语句不能被回滚，比如创建或取消数据库的语句，和创建、取消或更改表或存储的子程序的语句。</span><br><span class="line">2. 事务不能被嵌套</span><br></pre></td></tr></table></figure>

<h2 id="保存点"><a href="#保存点" class="headerlink" title="保存点"></a>保存点</h2><p>​    SAVEPOINT 保存点名称 – 设置一个事务保存点<br>​    ROLLBACK TO SAVEPOINT 保存点名称 – 回滚到保存点<br>​    RELEASE SAVEPOINT 保存点名称 – 删除保存点</p>
<h2 id="InnoDB自动提交特性设置"><a href="#InnoDB自动提交特性设置" class="headerlink" title="InnoDB自动提交特性设置"></a>InnoDB自动提交特性设置</h2><p>​    SET autocommit = 0|1;    0表示关闭自动提交，1表示开启自动提交。</p>
<ul>
<li>如果关闭了，那普通操作的结果对其他客户端也不可见，需要commit提交后才能持久化数据操作。<ul>
<li>也可以关闭自动提交来开启事务。但与START TRANSACTION不同的是，<br>SET autocommit是永久改变服务器的设置，直到下次再次修改该设置。(针对当前连接)<br>而START TRANSACTION记录开启前的状态，而一旦事务提交或回滚后就需要再次开启事务。(针对当前事务)</li>
</ul>
</li>
</ul>
<h1 id="锁表"><a href="#锁表" class="headerlink" title="锁表"></a>锁表</h1><p>表锁定只用于防止其它客户端进行不正当地读取和写入<br>MyISAM 支持表锁，InnoDB 支持行锁</p>
<h2 id="锁定"><a href="#锁定" class="headerlink" title="锁定"></a>锁定</h2><p>​    LOCK TABLES tbl_name [AS alias]</p>
<h2 id="解锁"><a href="#解锁" class="headerlink" title="解锁"></a>解锁</h2><p>​    UNLOCK TABLES</p>
<h1 id="触发器"><a href="#触发器" class="headerlink" title="触发器"></a>触发器</h1><p>​    触发程序是与表有关的命名数据库对象，当该表出现特定事件时，将激活该对象<br>​    监听：记录的增加、修改、删除。</p>
<h2 id="创建触发器"><a href="#创建触发器" class="headerlink" title="创建触发器"></a>创建触发器</h2><p>CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_stmt<br>    参数：<br>    trigger_time是触发程序的动作时间。它可以是 before 或 after，以指明触发程序是在激活它的语句之前或之后触发。<br>    trigger_event指明了激活触发程序的语句的类型<br>        INSERT：将新行插入表时激活触发程序<br>        UPDATE：更改某一行时激活触发程序<br>        DELETE：从表中删除某一行时激活触发程序<br>    tbl_name：监听的表，必须是永久性的表，不能将触发程序与TEMPORARY表或视图关联起来。<br>    trigger_stmt：当触发程序激活时执行的语句。执行多个语句，可使用BEGIN…END复合语句结构</p>
<h2 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h2><p>DROP TRIGGER [schema_name.]trigger_name</p>
<p>可以使用old和new代替旧的和新的数据<br>    更新操作，更新前是old，更新后是new.<br>    删除操作，只有old.<br>    增加操作，只有new.</p>
<h2 id="注意-1"><a href="#注意-1" class="headerlink" title="注意"></a>注意</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1. 对于具有相同触发程序动作时间和事件的给定表，不能有两个触发程序。</span><br></pre></td></tr></table></figure>

<h2 id="字符连接函数"><a href="#字符连接函数" class="headerlink" title="字符连接函数"></a>字符连接函数</h2><p>concat(str1[, str2,…])</p>
<p>– 分支语句<br>if 条件 then<br>    执行语句<br>elseif 条件 then<br>    执行语句<br>else<br>    执行语句<br>end if;</p>
<p>– 修改最外层语句结束符<br>delimiter 自定义结束符号<br>    SQL语句<br>自定义结束符号</p>
<p>delimiter ;        – 修改回原来的分号</p>
<h2 id="语句块包裹"><a href="#语句块包裹" class="headerlink" title="语句块包裹"></a>语句块包裹</h2><p>begin<br>    语句块<br>end</p>
<h2 id="特殊的执行"><a href="#特殊的执行" class="headerlink" title="特殊的执行"></a>特殊的执行</h2><ol>
<li>只要添加记录，就会触发程序。</li>
<li>Insert into on duplicate key update 语法会触发：<br>如果没有重复记录，会触发 before insert, after insert;<br>如果有重复记录并更新，会触发 before insert, before update, after update;<br>如果有重复记录但是没有发生更新，则触发 before insert, before update</li>
<li>Replace 语法 如果有记录，则执行 before insert, before delete, after delete, after insert</li>
</ol>
<h1 id="SQL编程"><a href="#SQL编程" class="headerlink" title="SQL编程"></a>SQL编程</h1><h2 id="局部变量"><a href="#局部变量" class="headerlink" title="局部变量"></a>局部变量</h2><h3 id="变量声明"><a href="#变量声明" class="headerlink" title="变量声明"></a>变量声明</h3><p>​    declare var_name[,…] type [default value]<br>​    这个语句被用来声明局部变量。要给变量提供一个默认值，请包含一个default子句。值可以被指定为一个表达式，不需要为一个常数。如果没有default子句，初始值为null。 </p>
<h3 id="赋值"><a href="#赋值" class="headerlink" title="赋值"></a>赋值</h3><p>​    使用 set 和 select into 语句为变量赋值。</p>
<ul>
<li>注意：在函数内是可以使用全局变量（用户自定义的变量）</li>
</ul>
<h2 id="全局变量"><a href="#全局变量" class="headerlink" title="全局变量"></a>全局变量</h2><h3 id="定义、赋值"><a href="#定义、赋值" class="headerlink" title="定义、赋值"></a>定义、赋值</h3><p>set 语句可以定义并为变量赋值。<br>set @var = value;<br>也可以使用select into语句为变量初始化并赋值。这样要求select语句只能返回一行，但是可以是多个字段，就意味着同时为多个变量进行赋值，变量的数量需要与查询的列数一致。<br>还可以把赋值语句看作一个表达式，通过select执行完成。此时为了避免=被当作关系运算符看待，使用:=代替。（set语句可以使用= 和 :=）。<br>select @var:=20;<br>select @v1:=id, @v2=name from t1 limit 1;<br>select * from tbl_name where @var:=30;</p>
<p>select into 可以将表中查询获得的数据赋给变量。<br>    -| select max(height) into @max_height from tb;</p>
<h3 id="自定义变量名"><a href="#自定义变量名" class="headerlink" title="自定义变量名"></a>自定义变量名</h3><p>为了避免select语句中，用户自定义的变量与系统标识符（通常是字段名）冲突，用户自定义变量在变量名前使用@作为开始符号。<br>@var=10;</p>
<p>变量被定义后，在整个会话周期都有效（登录到退出）</p>
<h2 id="控制结构"><a href="#控制结构" class="headerlink" title="控制结构"></a>控制结构</h2><h3 id="if语句"><a href="#if语句" class="headerlink" title="if语句"></a>if语句</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">if search_condition then </span><br><span class="line">    statement_list    </span><br><span class="line">[elseif search_condition then</span><br><span class="line">    statement_list]</span><br><span class="line">...</span><br><span class="line">[else</span><br><span class="line">    statement_list]</span><br><span class="line">end if;</span><br></pre></td></tr></table></figure>



<h3 id="case语句"><a href="#case语句" class="headerlink" title="case语句"></a>case语句</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CASE value WHEN [compare-value] THEN result</span><br><span class="line">[WHEN [compare-value] THEN result ...]</span><br><span class="line">[ELSE result]</span><br><span class="line">END</span><br></pre></td></tr></table></figure>



<h3 id="while循环"><a href="#while循环" class="headerlink" title="while循环"></a>while循环</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[begin_label:] while search_condition do</span><br><span class="line">    statement_list</span><br><span class="line">end while [end_label];</span><br></pre></td></tr></table></figure>



<ul>
<li><p>如果需要在循环内提前终止 while循环，则需要使用标签；标签需要成对出现。</p>
<p>– 退出循环</p>
<pre><code>退出整个循环 leave
退出当前循环 iterate
通过退出的标签决定退出哪个循环</code></pre></li>
</ul>
<h2 id="内置函数"><a href="#内置函数" class="headerlink" title="内置函数"></a>内置函数</h2><h3 id="数值函数"><a href="#数值函数" class="headerlink" title="数值函数"></a>数值函数</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">abs(x)            -- 绝对值 abs(-10.9) &#x3D; 10</span><br><span class="line">format(x, d)    -- 格式化千分位数值 format(1234567.456, 2) &#x3D; 1,234,567.46</span><br><span class="line">ceil(x)            -- 向上取整 ceil(10.1) &#x3D; 11</span><br><span class="line">floor(x)        -- 向下取整 floor (10.1) &#x3D; 10</span><br><span class="line">round(x)        -- 四舍五入去整</span><br><span class="line">mod(m, n)        -- m%n m mod n 求余 10%3&#x3D;1</span><br><span class="line">pi()            -- 获得圆周率</span><br><span class="line">pow(m, n)        -- m^n</span><br><span class="line">sqrt(x)            -- 算术平方根</span><br><span class="line">rand()            -- 随机数</span><br><span class="line">truncate(x, d)    -- 截取d位小数</span><br></pre></td></tr></table></figure>



<h3 id="时间日期函数"><a href="#时间日期函数" class="headerlink" title="时间日期函数"></a>时间日期函数</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">now(), current_timestamp();     -- 当前日期时间</span><br><span class="line">current_date();                    -- 当前日期</span><br><span class="line">current_time();                    -- 当前时间</span><br><span class="line">date(&#39;yyyy-mm-dd hh:ii:ss&#39;);    -- 获取日期部分</span><br><span class="line">time(&#39;yyyy-mm-dd hh:ii:ss&#39;);    -- 获取时间部分</span><br><span class="line">date_format(&#39;yyyy-mm-dd hh:ii:ss&#39;, &#39;%d %y %a %d %m %b %j&#39;);    -- 格式化时间</span><br><span class="line">unix_timestamp();                -- 获得unix时间戳</span><br><span class="line">from_unixtime();                -- 从时间戳获得时间</span><br></pre></td></tr></table></figure>



<h3 id="字符串函数"><a href="#字符串函数" class="headerlink" title="字符串函数"></a>字符串函数</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">length(string)            -- string长度，字节</span><br><span class="line">char_length(string)        -- string的字符个数</span><br><span class="line">substring(str, position [,length])        -- 从str的position开始,取length个字符</span><br><span class="line">replace(str ,search_str ,replace_str)    -- 在str中用replace_str替换search_str</span><br><span class="line">instr(string ,substring)    -- 返回substring首次在string中出现的位置</span><br><span class="line">concat(string [,...])    -- 连接字串</span><br><span class="line">charset(str)            -- 返回字串字符集</span><br><span class="line">lcase(string)            -- 转换成小写</span><br><span class="line">left(string, length)    -- 从string2中的左边起取length个字符</span><br><span class="line">load_file(file_name)    -- 从文件读取内容</span><br><span class="line">locate(substring, string [,start_position])    -- 同instr,但可指定开始位置</span><br><span class="line">lpad(string, length, pad)    -- 重复用pad加在string开头,直到字串长度为length</span><br><span class="line">ltrim(string)            -- 去除前端空格</span><br><span class="line">repeat(string, count)    -- 重复count次</span><br><span class="line">rpad(string, length, pad)    -- 在str后用pad补充,直到长度为length</span><br><span class="line">rtrim(string)            -- 去除后端空格</span><br><span class="line">strcmp(string1 ,string2)    -- 逐字符比较两字串大小</span><br></pre></td></tr></table></figure>



<h3 id="流程函数"><a href="#流程函数" class="headerlink" title="流程函数"></a>流程函数</h3><p>case when [condition] then result [when [condition] then result …] [else result] end   多分支<br>if(expr1,expr2,expr3)  双分支。</p>
<h3 id="聚合函数"><a href="#聚合函数" class="headerlink" title="聚合函数"></a>聚合函数</h3><p>count()<br>sum();<br>max();<br>min();<br>avg();<br>group_concat()</p>
<h3 id="其他常用函数"><a href="#其他常用函数" class="headerlink" title="其他常用函数"></a>其他常用函数</h3><p>md5();<br>default();</p>
<h2 id="存储函数，自定义函数"><a href="#存储函数，自定义函数" class="headerlink" title="存储函数，自定义函数"></a>存储函数，自定义函数</h2><h3 id="新建"><a href="#新建" class="headerlink" title="新建"></a>新建</h3><p>​    CREATE FUNCTION function_name (参数列表) RETURNS 返回值类型<br>​        函数体</p>
<p>函数名，应该合法的标识符，并且不应该与已有的关键字冲突。<br>一个函数应该属于某个数据库，可以使用db_name.funciton_name的形式执行当前函数所属数据库，否则为当前数据库。<br>参数部分，由”参数名”和”参数类型”组成。多个参数用逗号隔开。<br>函数体由多条可用的mysql语句，流程控制，变量声明等语句构成。<br>多条语句应该使用 begin…end 语句块包含。<br>一定要有 return 返回值语句。</p>
<h3 id="删除-1"><a href="#删除-1" class="headerlink" title="删除"></a>删除</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DROP FUNCTION [IF EXISTS] function_name;</span><br></pre></td></tr></table></figure>

<h3 id="查看"><a href="#查看" class="headerlink" title="查看"></a>查看</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SHOW FUNCTION STATUS LIKE &#39;partten&#39;</span><br><span class="line">SHOW CREATE FUNCTION function_name;</span><br></pre></td></tr></table></figure>

<h3 id="修改"><a href="#修改" class="headerlink" title="修改"></a>修改</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ALTER FUNCTION function_name 函数选项</span><br></pre></td></tr></table></figure>



<h2 id="存储过程，自定义功能"><a href="#存储过程，自定义功能" class="headerlink" title="存储过程，自定义功能"></a>存储过程，自定义功能</h2><h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>存储存储过程 是一段代码（过程），存储在数据库中的sql组成。<br>一个存储过程通常用于完成一段业务逻辑，例如报名，交班费，订单入库等。<br>而一个函数通常专注与某个功能，视为其他程序服务的，需要在其他语句中调用函数才可以，而存储过程不能被其他调用，是自己执行 通过call执行。</p>
<h3 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h3><p>CREATE PROCEDURE sp_name (参数列表)<br>    过程体</p>
<p>参数列表：不同于函数的参数列表，需要指明参数类型<br>IN，表示输入型<br>OUT，表示输出型<br>INOUT，表示混合型</p>
<p>注意，没有返回值。</p>
<h1 id="存储过程"><a href="#存储过程" class="headerlink" title="存储过程"></a>存储过程</h1><p>存储过程是一段可执行性代码的集合。相比函数，更偏向于业务逻辑。<br>调用：CALL 过程名<br>– 注意</p>
<ul>
<li>没有返回值。</li>
<li>只能单独调用，不可夹杂在其他语句中</li>
</ul>
<h2 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">IN|OUT|INOUT 参数名 数据类型</span><br><span class="line">IN        输入：在调用过程中，将数据输入到过程体内部的参数</span><br><span class="line">OUT        输出：在调用过程中，将过程体处理完的结果返回到客户端</span><br><span class="line">INOUT    输入输出：既可输入，也可输出</span><br></pre></td></tr></table></figure>



<h2 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CREATE PROCEDURE 过程名 (参数列表)</span><br><span class="line">BEGIN</span><br><span class="line">    -- 过程体</span><br><span class="line">END</span><br></pre></td></tr></table></figure>



<h1 id="用户和权限管理"><a href="#用户和权限管理" class="headerlink" title="用户和权限管理"></a>用户和权限管理</h1><p>用户信息表：mysql.user</p>
<h2 id="刷新权限"><a href="#刷新权限" class="headerlink" title="刷新权限"></a>刷新权限</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">FLUSH PRIVILEGES</span><br></pre></td></tr></table></figure>



<h2 id="增加用户"><a href="#增加用户" class="headerlink" title="增加用户"></a>增加用户</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CREATE USER 用户名 IDENTIFIED BY [PASSWORD] 密码(字符串)</span><br></pre></td></tr></table></figure>

<p>必须拥有mysql数据库的全局CREATE USER权限，或拥有INSERT权限。</p>
<p>只能创建用户，不能赋予权限。</p>
<p>用户名，注意引号：如 ‘user_name’@’192.168.1.1’</p>
<p>密码也需引号，纯数字密码也要加引号</p>
<p>要在纯文本中指定密码，需忽略PASSWORD关键词。要把密码指定为由PASSWORD()函数返回的混编值，需包含关键字PASSWORD</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">-- 重命名用户</span><br><span class="line">RENAME USER old_user TO new_user</span><br><span class="line">-- 设置密码</span><br><span class="line">SET PASSWORD &#x3D; PASSWORD(&#39;密码&#39;)    -- 为当前用户设置密码</span><br><span class="line">SET PASSWORD FOR 用户名 &#x3D; PASSWORD(&#39;密码&#39;)    -- 为指定用户设置密码</span><br><span class="line">-- 删除用户</span><br><span class="line">DROP USER 用户名</span><br><span class="line">-- 分配权限&#x2F;添加用户</span><br><span class="line">GRANT 权限列表 ON 表名 TO 用户名 [IDENTIFIED BY [PASSWORD] &#39;password&#39;]</span><br><span class="line">          </span><br><span class="line">- all privileges 表示所有权限</span><br><span class="line">-- 表示所有库的所有表</span><br><span class="line">- 库名.表名 表示某库下面的某表</span><br><span class="line">-- 查看权限</span><br><span class="line">SHOW GRANTS FOR 用户名</span><br><span class="line">-- 查看当前用户权限</span><br><span class="line">SHOW GRANTS; 或 SHOW GRANTS FOR CURRENT_USER; 或 SHOW GRANTS FOR CURRENT_USER();</span><br><span class="line">-- 撤消权限</span><br><span class="line">REVOKE 权限列表 ON 表名 FROM 用户名</span><br><span class="line">REVOKE ALL PRIVILEGES, GRANT OPTION FROM 用户名    -- 撤销所有权限</span><br><span class="line">-- 权限层级</span><br><span class="line">-- 要使用GRANT或REVOKE，您必须拥有GRANT OPTION权限，并且您必须用于您正在授予或撤销的权限。</span><br><span class="line">-- 全局层级：全局权限适用于一个给定服务器中的所有数据库，mysql.user</span><br><span class="line">GRANT ALL ON *.*和 REVOKE ALL ON *.*只授予和撤销全局权限。</span><br><span class="line">-- 数据库层级：数据库权限适用于一个给定数据库中的所有目标，mysql.db, mysql.host</span><br><span class="line">GRANT ALL ON db_name.*和REVOKE ALL ON db_name.*只授予和撤销数据库权限。</span><br><span class="line">-- 表层级：表权限适用于一个给定表中的所有列，mysql.talbes_priv</span><br><span class="line">GRANT ALL ON db_name.tbl_name和REVOKE ALL ON db_name.tbl_name -- 只授予和撤销表权限。</span><br><span class="line">-- 列层级：列权限适用于一个给定表中的单一列，mysql.columns_priv</span><br><span class="line">-- 当使用REVOKE时，您必须指定与被授权列相同的列。</span><br><span class="line">-- 权限列表</span><br><span class="line">ALL [PRIVILEGES]    -- 设置除GRANT OPTION之外的所有简单权限</span><br><span class="line">ALTER    -- 允许使用ALTER TABLE</span><br><span class="line">ALTER ROUTINE    -- 更改或取消已存储的子程序</span><br><span class="line">CREATE    -- 允许使用CREATE TABLE</span><br><span class="line">CREATE ROUTINE    -- 创建已存储的子程序</span><br><span class="line">CREATE TEMPORARY TABLES        -- 允许使用CREATE TEMPORARY TABLE</span><br><span class="line">CREATE USER        -- 允许使用CREATE USER, DROP USER, RENAME USER和REVOKE ALL PRIVILEGES。</span><br><span class="line">CREATE VIEW        -- 允许使用CREATE VIEW</span><br><span class="line">DELETE    -- 允许使用DELETE</span><br><span class="line">DROP    -- 允许使用DROP TABLE</span><br><span class="line">EXECUTE        -- 允许用户运行已存储的子程序</span><br><span class="line">FILE    -- 允许使用SELECT...INTO OUTFILE和LOAD DATA INFILE</span><br><span class="line">INDEX     -- 允许使用CREATE INDEX和DROP INDEX</span><br><span class="line">INSERT    -- 允许使用INSERT</span><br><span class="line">LOCK TABLES        -- 允许对您拥有SELECT权限的表使用LOCK TABLES</span><br><span class="line">PROCESS     -- 允许使用SHOW FULL PROCESSLIST</span><br><span class="line">REFERENCES    -- 未被实施</span><br><span class="line">RELOAD    -- 允许使用FLUSH</span><br><span class="line">REPLICATION CLIENT    -- 允许用户询问从属服务器或主服务器的地址</span><br><span class="line">REPLICATION SLAVE    -- 用于复制型从属服务器（从主服务器中读取二进制日志事件）</span><br><span class="line">SELECT    -- 允许使用SELECT</span><br><span class="line">SHOW DATABASES    -- 显示所有数据库</span><br><span class="line">SHOW VIEW    -- 允许使用SHOW CREATE VIEW</span><br><span class="line">SHUTDOWN    -- 允许使用mysqladmin shutdown</span><br><span class="line">SUPER    -- 允许使用CHANGE MASTER, KILL, PURGE MASTER LOGS和SET GLOBAL语句，mysqladmin debug命令；允许您连接（一次），即使已达到max_connections。</span><br><span class="line">UPDATE    -- 允许使用UPDATE</span><br><span class="line">USAGE    -- “无权限”的同义词</span><br><span class="line">GRANT OPTION    -- 允许授予权限</span><br></pre></td></tr></table></figure>

<p>​              </p>
<h1 id="表维护"><a href="#表维护" class="headerlink" title="表维护"></a>表维护</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">-- 分析和存储表的关键字分布</span><br><span class="line">ANALYZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE 表名 ...</span><br><span class="line">-- 检查一个或多个表是否有错误</span><br><span class="line">CHECK TABLE tbl_name [, tbl_name] ... [option] ...</span><br><span class="line">option &#x3D; &#123;QUICK | FAST | MEDIUM | EXTENDED | CHANGED&#125;</span><br><span class="line">-- 整理数据文件的碎片</span><br><span class="line">OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...</span><br></pre></td></tr></table></figure>

<h1 id="杂项"><a href="#杂项" class="headerlink" title="杂项"></a>杂项</h1><ol>
<li>可用反引号（`）为标识符（库名、表名、字段名、索引、别名）包裹，以避免与关键字重名！中文也可以作为标识符！</li>
<li>每个库目录存在一个保存当前数据库的选项文件db.opt。</li>
<li>注释：<br>单行注释 # 注释内容<br>多行注释 /* 注释内容 */<br>单行注释 – 注释内容        (标准SQL注释风格，要求双破折号后加一空格符（空格、TAB、换行等）)</li>
<li>模式通配符：<br>_    任意单个字符<br>%    任意多个字符，甚至包括零字符<br>单引号需要进行转义 &#39;</li>
<li>CMD命令行内的语句结束符可以为 “;”, “\G”, “\g”，仅影响显示结果。其他地方还是用分号结束。delimiter 可修改当前对话的语句结束符。</li>
<li>SQL对大小写不敏感</li>
<li>清除已有语句：\c</li>
</ol>

    </div>

    
    
    

    
    <div>    
      
        <ul class="post-copyright">
          <li class="post-copyright-link">
          <strong>本文作者：</strong>
          <a href="/" title="欢迎访问 Chenyumeng 的个人博客">Chenyumeng</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文标题：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/03/15/MySQL/" title="MySQL命令">MySQL命令</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文链接：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/03/15/MySQL/" title="MySQL命令">https://ipvb.gitee.io/blog/2020/03/15/MySQL/</a>
          </li>

          <li class="post-copyright-date">
            <strong>发布时间： </strong>2020年3月15日 - 16时03分
          </li>  

          <li class="post-copyright-license">
            <strong>版权声明： </strong>
            本文由 Chenyumeng 原创。
          </li>
        </ul>
      
    </div>
      
  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\16\linux MySQL安装\" rel="bookmark">linux MySQL安装</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\css\" rel="bookmark">css格式化</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\idea\" rel="bookmark">idea快捷键</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\git\" rel="bookmark">git命令</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\webstorm\" rel="bookmark">webstorm快捷键</a></div>
    </li>
  </ul>

        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/images/wechatpay.png" alt="Chenyumeng 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/images/alipay.png" alt="Chenyumeng 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <div>
        
          <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------　　　　本文结束　<i class="fa fa-heart"></i>　感谢您的阅读　　　　-------------</div>
    
</div>
        
      </div>

      <footer class="post-footer">
          
          <div class="post-tags">
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2020/03/15/git/" rel="prev" title="git命令">
      <i class="fa fa-chevron-left"></i> git命令
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/03/15/nginx/" rel="next" title="nginx安装配置笔记">
      nginx安装配置笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

    <!-- 引入share.js -->
    
      <div data-weibo-title="分享到微博" data-qq-title="分享到QQ" data-douban-title="分享到豆瓣" class="social-share" class="share-component" data-disabled="twitter,facebook" data-description="Share.js - 一键分享到微博，QQ空间，腾讯微博，人人，豆瓣">分享到：</div>
    
  </div>


          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC80OTExNy8yNTYxMg=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#启动MySQL"><span class="nav-number">1.</span> <span class="nav-text">启动MySQL</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#连接与断开服务器"><span class="nav-number">2.</span> <span class="nav-text">连接与断开服务器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#跳过权限验证登录MySQL"><span class="nav-number">3.</span> <span class="nav-text">跳过权限验证登录MySQL</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改root密码"><span class="nav-number">4.</span> <span class="nav-text">修改root密码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数据库操作"><span class="nav-number"></span> <span class="nav-text">数据库操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#查看当前数据库"><span class="nav-number">1.</span> <span class="nav-text">查看当前数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#显示当前时间、用户名、数据库版本"><span class="nav-number">2.</span> <span class="nav-text">显示当前时间、用户名、数据库版本</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建库"><span class="nav-number">3.</span> <span class="nav-text">创建库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看已有库"><span class="nav-number">4.</span> <span class="nav-text">查看已有库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看当前库信息"><span class="nav-number">5.</span> <span class="nav-text">查看当前库信息</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改库的选项信息"><span class="nav-number">6.</span> <span class="nav-text">修改库的选项信息</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除库"><span class="nav-number">7.</span> <span class="nav-text">删除库</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#表的操作"><span class="nav-number"></span> <span class="nav-text">表的操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建表"><span class="nav-number">1.</span> <span class="nav-text">创建表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#表选项"><span class="nav-number">2.</span> <span class="nav-text">表选项</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#字符集"><span class="nav-number">2.1.</span> <span class="nav-text">字符集</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#存储引擎"><span class="nav-number">2.2.</span> <span class="nav-text">存储引擎</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据文件目录"><span class="nav-number">2.3.</span> <span class="nav-text">数据文件目录</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#索引文件目录"><span class="nav-number">2.4.</span> <span class="nav-text">索引文件目录</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#表注释"><span class="nav-number">2.5.</span> <span class="nav-text">表注释</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分区选项"><span class="nav-number">2.6.</span> <span class="nav-text">分区选项</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看所有表"><span class="nav-number">3.</span> <span class="nav-text">查看所有表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看表机构"><span class="nav-number">4.</span> <span class="nav-text">查看表机构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改表"><span class="nav-number">5.</span> <span class="nav-text">修改表</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#修改表本身的选项"><span class="nav-number">5.1.</span> <span class="nav-text">修改表本身的选项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#对表进行重命名"><span class="nav-number">5.2.</span> <span class="nav-text">对表进行重命名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修改表的字段机构"><span class="nav-number">5.3.</span> <span class="nav-text">修改表的字段机构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#操作名"><span class="nav-number">5.3.1.</span> <span class="nav-text">操作名</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除表"><span class="nav-number">6.</span> <span class="nav-text">删除表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#清空表数据"><span class="nav-number">7.</span> <span class="nav-text">清空表数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#复制表结构"><span class="nav-number">8.</span> <span class="nav-text">复制表结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#复制表结构和数据"><span class="nav-number">9.</span> <span class="nav-text">复制表结构和数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#检查表是否有错误"><span class="nav-number">10.</span> <span class="nav-text">检查表是否有错误</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#优化表"><span class="nav-number">11.</span> <span class="nav-text">优化表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修复表"><span class="nav-number">12.</span> <span class="nav-text">修复表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分析表"><span class="nav-number">13.</span> <span class="nav-text">分析表</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数据操作"><span class="nav-number"></span> <span class="nav-text">数据操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#增"><span class="nav-number">1.</span> <span class="nav-text">增</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查"><span class="nav-number">2.</span> <span class="nav-text">查</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删"><span class="nav-number">3.</span> <span class="nav-text">删</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#改"><span class="nav-number">4.</span> <span class="nav-text">改</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#字符集编码"><span class="nav-number"></span> <span class="nav-text">字符集编码</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数据类型（列类型）"><span class="nav-number"></span> <span class="nav-text">数据类型（列类型）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#数值类型"><span class="nav-number">1.</span> <span class="nav-text">数值类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#整型"><span class="nav-number">1.1.</span> <span class="nav-text">整型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#浮点型"><span class="nav-number">1.2.</span> <span class="nav-text">浮点型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#"><span class="nav-number">1.3.</span> <span class="nav-text"></span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定点数"><span class="nav-number">1.4.</span> <span class="nav-text">定点数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字符串类型"><span class="nav-number">2.</span> <span class="nav-text">字符串类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#char-varchar"><span class="nav-number">2.1.</span> <span class="nav-text">char, varchar</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#blob-text"><span class="nav-number">2.2.</span> <span class="nav-text">blob, text</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#binary-varbinary"><span class="nav-number">2.3.</span> <span class="nav-text">binary, varbinary</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日期时间类型"><span class="nav-number">3.</span> <span class="nav-text">日期时间类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#枚举和集合"><span class="nav-number">4.</span> <span class="nav-text">枚举和集合</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#枚举-enum"><span class="nav-number">4.1.</span> <span class="nav-text">枚举(enum)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#集合（set）"><span class="nav-number">4.2.</span> <span class="nav-text">集合（set）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#选择类型"><span class="nav-number">5.</span> <span class="nav-text">选择类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#PHP角度"><span class="nav-number">5.1.</span> <span class="nav-text">PHP角度</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IP存储"><span class="nav-number">5.2.</span> <span class="nav-text">IP存储</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#列属性（列约束）"><span class="nav-number"></span> <span class="nav-text">列属性（列约束）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#主键"><span class="nav-number">1.</span> <span class="nav-text">主键</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#unique-唯一索引（唯一约束）"><span class="nav-number">2.</span> <span class="nav-text">unique 唯一索引（唯一约束）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#null-约束"><span class="nav-number">3.</span> <span class="nav-text">null 约束</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#default-默认值属性"><span class="nav-number">4.</span> <span class="nav-text">default 默认值属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#auto-increment-自动增长约束"><span class="nav-number">5.</span> <span class="nav-text">auto_increment 自动增长约束</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#comment-注释"><span class="nav-number">6.</span> <span class="nav-text">comment 注释</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#foreign-key-外键约束"><span class="nav-number">7.</span> <span class="nav-text">foreign key 外键约束</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如果指定了-on-update-或-on-delete：在删除或更新时，有如下几个操作可以选择："><span class="nav-number">8.</span> <span class="nav-text">如果指定了 on update 或 on delete：在删除或更新时，有如下几个操作可以选择：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#建表规范"><span class="nav-number"></span> <span class="nav-text">建表规范</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#select"><span class="nav-number"></span> <span class="nav-text">select</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#select-expr"><span class="nav-number">1.</span> <span class="nav-text">select_expr</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#from-子句"><span class="nav-number">2.</span> <span class="nav-text">from 子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#where-子句"><span class="nav-number">3.</span> <span class="nav-text">where 子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#group-by-子句-分组子句"><span class="nav-number">4.</span> <span class="nav-text">group by 子句, 分组子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#having-子句，条件子句"><span class="nav-number">5.</span> <span class="nav-text">having 子句，条件子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#order-by-子句，排序子句"><span class="nav-number">6.</span> <span class="nav-text">order by 子句，排序子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#limit-子句，限制结果数量子句"><span class="nav-number">7.</span> <span class="nav-text">limit 子句，限制结果数量子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#distinct-all-选项"><span class="nav-number">8.</span> <span class="nav-text">distinct, all 选项</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#UNION"><span class="nav-number"></span> <span class="nav-text">UNION</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#子查询"><span class="nav-number"></span> <span class="nav-text">子查询</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#特殊运算符"><span class="nav-number">1.</span> <span class="nav-text">特殊运算符</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#连接查询-join"><span class="nav-number"></span> <span class="nav-text">连接查询(join)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#内连接-inner-join"><span class="nav-number">1.</span> <span class="nav-text">内连接(inner join)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#交叉连接-cross-join"><span class="nav-number">2.</span> <span class="nav-text">交叉连接 cross join</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#外连接-outer-join"><span class="nav-number">3.</span> <span class="nav-text">外连接(outer join)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#导入导出"><span class="nav-number"></span> <span class="nav-text">导入导出</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#控制格式"><span class="nav-number">1.</span> <span class="nav-text">控制格式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#insert"><span class="nav-number"></span> <span class="nav-text">insert</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#delete"><span class="nav-number"></span> <span class="nav-text">delete</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#truncate"><span class="nav-number"></span> <span class="nav-text">truncate</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#备份与还原"><span class="nav-number"></span> <span class="nav-text">备份与还原</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#导出"><span class="nav-number">1.</span> <span class="nav-text">导出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#导入"><span class="nav-number">2.</span> <span class="nav-text">导入</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#视图"><span class="nav-number"></span> <span class="nav-text">视图</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建视图"><span class="nav-number">1.</span> <span class="nav-text">创建视图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看结构"><span class="nav-number">2.</span> <span class="nav-text">查看结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除视图"><span class="nav-number">3.</span> <span class="nav-text">删除视图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改视图结构"><span class="nav-number">4.</span> <span class="nav-text">修改视图结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#视图作用"><span class="nav-number">5.</span> <span class="nav-text">视图作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#视图算法-ALGORITHM"><span class="nav-number">6.</span> <span class="nav-text">视图算法(ALGORITHM)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#事务-transaction"><span class="nav-number"></span> <span class="nav-text">事务(transaction)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#事务开启"><span class="nav-number">1.</span> <span class="nav-text">事务开启</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务提交"><span class="nav-number">2.</span> <span class="nav-text">事务提交</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务回滚"><span class="nav-number">3.</span> <span class="nav-text">事务回滚</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务的特性"><span class="nav-number">4.</span> <span class="nav-text">事务的特性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#原子性（Atomicity）"><span class="nav-number">4.1.</span> <span class="nav-text">原子性（Atomicity）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一致性（Consistency）"><span class="nav-number">4.2.</span> <span class="nav-text">一致性（Consistency）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#隔离性（Isolation）"><span class="nav-number">4.3.</span> <span class="nav-text">隔离性（Isolation）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#持久性（Durability）"><span class="nav-number">4.4.</span> <span class="nav-text">持久性（Durability）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务的实现"><span class="nav-number">5.</span> <span class="nav-text">事务的实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务的原理"><span class="nav-number">6.</span> <span class="nav-text">事务的原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注意"><span class="nav-number">7.</span> <span class="nav-text">注意</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#保存点"><span class="nav-number">8.</span> <span class="nav-text">保存点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#InnoDB自动提交特性设置"><span class="nav-number">9.</span> <span class="nav-text">InnoDB自动提交特性设置</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#锁表"><span class="nav-number"></span> <span class="nav-text">锁表</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#锁定"><span class="nav-number">1.</span> <span class="nav-text">锁定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#解锁"><span class="nav-number">2.</span> <span class="nav-text">解锁</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#触发器"><span class="nav-number"></span> <span class="nav-text">触发器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建触发器"><span class="nav-number">1.</span> <span class="nav-text">创建触发器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除"><span class="nav-number">2.</span> <span class="nav-text">删除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注意-1"><span class="nav-number">3.</span> <span class="nav-text">注意</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字符连接函数"><span class="nav-number">4.</span> <span class="nav-text">字符连接函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#语句块包裹"><span class="nav-number">5.</span> <span class="nav-text">语句块包裹</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#特殊的执行"><span class="nav-number">6.</span> <span class="nav-text">特殊的执行</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#SQL编程"><span class="nav-number"></span> <span class="nav-text">SQL编程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#局部变量"><span class="nav-number">1.</span> <span class="nav-text">局部变量</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#变量声明"><span class="nav-number">1.1.</span> <span class="nav-text">变量声明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#赋值"><span class="nav-number">1.2.</span> <span class="nav-text">赋值</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#全局变量"><span class="nav-number">2.</span> <span class="nav-text">全局变量</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义、赋值"><span class="nav-number">2.1.</span> <span class="nav-text">定义、赋值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义变量名"><span class="nav-number">2.2.</span> <span class="nav-text">自定义变量名</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#控制结构"><span class="nav-number">3.</span> <span class="nav-text">控制结构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#if语句"><span class="nav-number">3.1.</span> <span class="nav-text">if语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#case语句"><span class="nav-number">3.2.</span> <span class="nav-text">case语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#while循环"><span class="nav-number">3.3.</span> <span class="nav-text">while循环</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内置函数"><span class="nav-number">4.</span> <span class="nav-text">内置函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数值函数"><span class="nav-number">4.1.</span> <span class="nav-text">数值函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#时间日期函数"><span class="nav-number">4.2.</span> <span class="nav-text">时间日期函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串函数"><span class="nav-number">4.3.</span> <span class="nav-text">字符串函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#流程函数"><span class="nav-number">4.4.</span> <span class="nav-text">流程函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#聚合函数"><span class="nav-number">4.5.</span> <span class="nav-text">聚合函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其他常用函数"><span class="nav-number">4.6.</span> <span class="nav-text">其他常用函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#存储函数，自定义函数"><span class="nav-number">5.</span> <span class="nav-text">存储函数，自定义函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#新建"><span class="nav-number">5.1.</span> <span class="nav-text">新建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除-1"><span class="nav-number">5.2.</span> <span class="nav-text">删除</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查看"><span class="nav-number">5.3.</span> <span class="nav-text">查看</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修改"><span class="nav-number">5.4.</span> <span class="nav-text">修改</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#存储过程，自定义功能"><span class="nav-number">6.</span> <span class="nav-text">存储过程，自定义功能</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义"><span class="nav-number">6.1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建"><span class="nav-number">6.2.</span> <span class="nav-text">创建</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#存储过程"><span class="nav-number"></span> <span class="nav-text">存储过程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#参数"><span class="nav-number">1.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#语法"><span class="nav-number">2.</span> <span class="nav-text">语法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#用户和权限管理"><span class="nav-number"></span> <span class="nav-text">用户和权限管理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#刷新权限"><span class="nav-number">1.</span> <span class="nav-text">刷新权限</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#增加用户"><span class="nav-number">2.</span> <span class="nav-text">增加用户</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#表维护"><span class="nav-number"></span> <span class="nav-text">表维护</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#杂项"><span class="nav-number"></span> <span class="nav-text">杂项</span></a></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Chenyumeng"
      src="/blog/images/touxiang.JPG">
  <p class="site-author-name" itemprop="name">Chenyumeng</p>
  <div class="site-description" itemprop="description">用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">32</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">29</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/chen-yumeng" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;chen-yumeng" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/3123221441" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;3123221441" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://github.com/" title="https:&#x2F;&#x2F;github.com&#x2F;" rel="noopener" target="_blank">Github</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chenyumeng</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">390k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">5:55</span>
</div>

        






  <script>
  function leancloudSelector(url) {
    url = encodeURI(url);
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.id);
      var title = visitors.dataset.flagTitle;

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url })))
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .catch(error => {
                console.error('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title, url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.id);
      });

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url: { '$in': entries } })))
        .then(response => response.json())
        .then(({ results }) => {
          for (let url of entries) {
            let target = results.find(item => item.url === url);
            leancloudSelector(url).innerText = target ? target.time : 0;
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method,
          headers: {
            'X-LC-Id'     : '',
            'X-LC-Key'    : '',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script>


      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

  <script src="/dist/js/social-share.min.js"></script>
</body>
</html>
